$(function(){
	$('.mc').css('display','none');
	$('#categorys').hover(function(){
		$(this).children('.mc').toggle();
	});

	var keyPid = $Util.getQueryString(document.location.search,'pid');
	var level = $Util.getQueryString(document.location.search,'level');
	var keyword = $Util.getQueryString(document.location.search,'keyword');
	var skeyword = $Util.getQueryString(document.location.search,'skeyword');
	var isAll = $Util.getQueryString(document.location.search,'is_all');
	
	if (keyword) {
		var kw = decodeURI(keyword);
		var fkey = $Util.getQueryString(document.location.search,'fkey');
		if (fkey) {
			$('#fkey').attr('value',decodeURI(fkey));
			kw += '/'+decodeURI(fkey);
		}
		getCategoryList(1,keyPid);
		getProductList(kw);
	}
	
	if (skeyword || isAll) {
		$('#keyword').attr('value',decodeURI(skeyword));
		$('#pKeywordName').html('母婴：');
		getCategoryList(0,100000000);
		getProductList(decodeURI(skeyword));
	}
	
	var str = [' &gt;&nbsp;<a href="/product/list.html?is_all=1">母婴</a>'].join('');
	$('#linkDesc').after(str);
	
	if (level && level == 2) {
		$('#optionDiv').show();
	} else {
		$('#optionDiv').hide();
		$('#categoryList').html('');
	}
	
	getPlateProductList();
	getBrowsedMcList();
	
	$('#login_btn').bind('click', subLoginFrm);
	$('#reg_btn').bind('click', subRegFrm);
});

function getCategoryList(type,keyPid) {
	var url = '/json?action=QUERY_T_KEYWORD_BY_P_KEYWORD_ID_ACTION&P_KEYWORD_ID='+keyPid;
	if (type == 0) {
		$UI.listPage(url,'T_NAV_KEYWORD','#cKeywordList',printRootKeywordRes,'');
	} else {
		$UI.listPage(url,'T_NAV_KEYWORD','#pKeywordName',printKeywordRes,'');
	}
}

function printRootKeywordRes(obj,result,i,n,total) {
	var div = '';
	div += [
		'<li>',
		'<a href="#" onclick="changeBrandCss(\'brand_'+i+'\');return false;" id="brand_'+i+'" name="brand">',
		obj.KEYWORD_NAME,
		'</a>',
		'</li>'
	].join('');
	$('#cKeywordList').append(div); 
}

function printKeywordRes(obj,result,i,n,total) {
	if (i == 0) {
		var pkeyword = $Util.getQueryString(document.location.search,'pkeyword');
		$(result).html(decodeURI(pkeyword)+'：');
	}
	var level = $Util.getQueryString(document.location.search,'level');
	if (obj.IS_HOT == 1 || level == 3) {
		var keyword = $Util.getQueryString(document.location.search,'keyword');
		var keyPid = $Util.getQueryString(document.location.search,'pid');
		var style = '';
		if (decodeURI(keyword) == obj.KEYWORD_NAME) style = 'on';
		var div = '';
		div += [
			'<li>',
			'<a href="#" class="'+style+'" onclick="changeBrandCss(\'brand_'+i+'\');return false;" id="brand_'+i+'" name="brand">',
			obj.KEYWORD_NAME,
			'</a>',
			'</li>'
		].join('');
		$('#cKeywordList').append(div);
	} else {
		if (level && level == 2) {
			var selectDiv = ['&nbsp;<select id="category_',i,'" name="category" onchange="doSearch();">'].join('');
			selectDiv += ['<option value="">',obj.KEYWORD_NAME,'</option>'].join('');
			
			if (obj.KEYWORD_CHILDS.length > 0) {
				$.each(obj.KEYWORD_CHILDS,function(c,e){
					selectDiv += ['<option value="',e.keywordName,'">',e.keywordName,'</option>'].join('');
				});
			}
			selectDiv += '</select>&nbsp;';
			$('#categoryList').append(selectDiv);
		}
	}
}

function changeBrandCss(id){
	$('#cKeywordList>li>a').removeClass('on');
	if (id) {
		$('#'+id).addClass('on');
	}
	doSearch();
}

function doSearch() {
	var queryStr = '';
	$.each($('a[name="brand"]'),function(i,n){
		if ($(this).attr('class') == 'on') {
			queryStr += decodeURI($(this).html());
			return false;
		}
	});
	var fkey = $Util.getQueryString(document.location.search,'fkey');
	if (fkey) {
		queryStr += '/' + decodeURI(fkey);
	}
	var skeyword = $Util.getQueryString(document.location.search,'skeyword');
	if (skeyword) {
		queryStr += '/' + decodeURI(skeyword);
	}
	var categorys = '';
	$.each($('select[name="category"]'),function(i,n){
		if ($(this).val()) {
			if (categorys) {
				categorys += '/' + decodeURI($(this).val());
			} else {
				categorys += decodeURI($(this).val());
			}
		}
	});
//	var isAll = $Util.getQueryString(document.location.search,'is_all');
//	if (isAll) queryStr = '';
	if (!categorys) {
		if (skeyword) categorys = decodeURI(skeyword);
	}
	getProductList(queryStr,categorys);
}

function getProductList(keyword,categorys) {
	var url = '/json?action=QUERY_T_PRODUCT_BY_KEYWORD_BY_PAGER_ACTION';
	url += ['&PRODUCT_KEYWORD=',keyword].join('');
	if (categorys) url += ['&CATEGORY_NAME=',categorys].join('');
	var css = $('#hbutton').attr('class');
	var orderBy = 0;
	if (css == 'hbutton1') {
		orderBy = 0;
	} else if (css == 'hbutton2') {
		orderBy = 1;
	} else if (css == 'hbutton3') {
		orderBy = 4;
	} else if (css == 'hbutton4') {
		orderBy = 2;
	} else if (css == 'hbutton5') {
		orderBy = 3;
	}
	url += '&ORDER_BY='+orderBy;
	var pageSize = 25;
	var defaultHtml = '<li><em style="text-align: center;width:100%">没有搜索到您要查询的商品...</em></li>';
	var current = $Util.getQueryString(document.location.search,'current');
	$UI.changePage(url,pageSize,'T_PRODUCT','#productList',printProduct,'#pager',defaultHtml,current,'#topPagePanel');
}

function printProduct(obj,result,i,n,len,c,t) {
	if (t) {
		$('#totalProducts').html('共<strong>'+t+'</strong>个商品');
		$('#pageShow').html(c+'/'+(Math.floor(t/25)+1));
	}
	var div = '';
	if ((i+1)%5 == 1) {
		div += '<ul class="ml30 lh" id="pro_row_'+Math.ceil((i+1)/5)+'">';
	}
	div += [
		'<li>',
			'<a href="javascript:void(0);" onclick="productDetail(',obj.PRODUCT_ID,')">',
			'<img src="../upload/product/',obj.PRODUCT_NO,'.jpg"  width="160" height="160" onmouseover="this.style.border = \'1px solid #ccc\'" onmouseout="this.style.border = \'\'"/></a>',
			'<h6><a href="javascript:void(0);" onclick="productDetail(',obj.PRODUCT_ID,')">',obj.PRODUCT_NAME,'</a></h6>',
			'<p class="cDGray tc">金麒价：<strong>￥',obj.MEMBER_PRICE,'</strong></p>',
			'<p class="fct10">',
				'<input type="button" onclick="addCart(',obj.PRODUCT_ID,',this)" class="btn_shop" value="放入购物车" />',
				'&nbsp;&nbsp;&nbsp;',
				'<input type="button" onclick="favProduct(',obj.PRODUCT_ID,',this)" class="btn_collect" value="收藏" />',
			'</p>',
		'</li>'
	].join('');
	if ((i+1)%5 == 1) {
		div += '</ul>';
		$(result).append(div);
	} else {
		$('#pro_row_'+Math.ceil((i+1)/5)).append(div);
	}
//	if(i == len - 1){
//		$("img").lazyload();
//		$("li>textarea").lazyload({placeholder : "../images/no_pic.gif",effect : "fadeIn"});
//	}
}

function subLoginFrm(){
	if(!winForm.checkLoginForm()){
		return;
	}
	
	var options = {
	    dataType: 'json',
	    success: function(data) {
	    	if(data.success){
	    		$.zxxbox.hide();
	    		getMemberSession();
	    		getCart();
	      	} else {
	      		var o = $('#win_login_message');
	      		o.html(data.errors.errmsg);
	      		o.show();
	      	}
	   	}
	};
	$.ajaxSetup({contentType:'application/x-www-form-urlencoded;charset=utf-8'});
    $('#login_frm').ajaxSubmit(options);
}

function subRegFrm(){
	if(!winForm.checkRegForm()){
		return;
	}
	var options = {
	    dataType: 'json',
	    success: function(data) {
	    	if(data.success){
	    		$.zxxbox.hide();
	      		getMemberSession();
	      		getCart();
	      	} else {
	      		var o = $('#win_reg_message');
	      		o.html(data.errors.errmsg);
	      		o.show();
	      		drawWinValidateCode();
	      	}
	   	}
	};
	$.ajaxSetup({contentType:'application/x-www-form-urlencoded;charset=utf-8'});
    $('#reg_frm').ajaxSubmit(options);
}

function addCart(id,btn){
	var url = '/json?action=ADD_PRODUCT_TO_CART_ACTION';
	$.post(url,{
			PRODUCT_ID:id,
			QTY : 1
		},function(data){
		if (data.success) {
			var tip = $('#success_tip');
			$('#info_tip').html('已加入购物车');
			showTip(tip,btn,10);
			
			getCart();
		} else {
			alert(data.errors.errmsg);
		}
	},'json');
}

function favProduct(id,btn){
	$.ajax({
		type : 'POST',
		url : '/json?action=GET_MEMBER_SESSION_ACTION',
		cache : false,
		async : false,
		dataType : 'json',
		success : function(data){
			if(data.success){
				var obj  = data.root.MEMBER_SESSION;
				if(obj == undefined){
					$("#tclogincon").zxxbox({
						title : '登录/注册',
						show : winForm.clearTip()
					});
					drawWinValidateCode();
				} else {
					var url = '/json?action=ADD_T_PRODUCT_FAVORITES_ACTION&PRODUCT_ID=' + id;
					$.post(url,{}, function(data){
						if(data.success){
							var tip = $('#success_tip');
							$('#info_tip').html('已加入收藏夹');
							showTip(tip,btn,100);
						}
					},'json');
				}
			}
		}
	});
}

var timer;
function showTip(tip, btn, left){
	var offset = $(btn).offset();
	tip.css('left', offset.left - left);
	tip.css('top', offset.top);
	tip.show();
	
	if (timer) {
		clearTimeout(timer);
	}
	timer = setTimeout("closeTip()", 1000);
}

function closeTip() {
	$('#success_tip').fadeOut('slow');
	timer=null;
}

function productDetail(id){
	$Product.click(id);
	window.open('file.html?id='+ id);
}

function getPlateProductList() {
	var url = '/json?action=QUERY_T_PLATE_PRODUCT_ACTION';
	$UI.listPage(url,'T_PLATE_PRODUCT','#newList',printPlateProductRes,'');
}

function printPlateProductRes(obj,result,i,n,total) {
	var panel = '';
	switch(obj.PLATE_CODE) {
		// 新品上市
		case '1012':
			panel = '#newList';
			break;
		// 热销商品
		case '1013':
			panel = '#hotItemList';
			break;
		default:
			break;
	}
	if (panel && obj.PRODUCT_LIST.length>0) {
		$.each(obj.PRODUCT_LIST,function(j,m){
			if ($(panel+'>li').length>2) return true;
			var appendStr = [
				'<li>',
				'<a href="file.html?id=',m.productId,'">','<img src="../upload/product/',m.productNo,'.jpg" width="160" height="160"/>','</a>',
				'<p>','<a href="file.html?id=',m.productId,'">',m.productName,'</a>','</p>',
				'<p class="cDGray">金麒价：','<strong>￥',m.memberPrice,'</strong>','</p>',
				'</li>'
			].join('');
			$(panel).append(appendStr);
		});
	}
}

function getBrowsedMcList() {
	var mcRs = $.cookie('browsedMc');
	if (mcRs) {
		var res = JSON.parse(mcRs);
		var newRes = res.reverse();
		var divStr = '';
		$.each(newRes,function(i,n){
			divStr += [
				'<li>',
				'<a href="file.html?id=',n.id,'">','<img src="',n.imgUrl,'" width="160" height="160"/>','</a>',
				'<p>','<a href="file.html?id=',n.id,'">',n.name,'</a>','</p>',
				'<p class="cDGray">金麒价：<strong>￥',n.price,'</strong>','</p>',
				'</li>'
			].join('');
		});
		$('#browseMcList').append(divStr);
	}
}

function changeStyle(css,obj) {
	if (obj.id) {
		if (obj.id == 'sellUp') {
			if($('#hbutton').attr('class') != 'hbutton2') {
				$(obj).attr('title','销量由高到低');
				$('#hbutton').removeClass().addClass(css);
			} else if ($('#hbutton').attr('class') == 'hbutton2') {
				$(obj).attr('title','销量由低到高');
				$('#hbutton').removeClass().addClass('hbutton4');		
			}
		} else if (obj.id == 'priceDown') {
			if($('#hbutton').attr('class') != 'hbutton3') {
				$(obj).attr('title','价格由低到高');
				$('#hbutton').removeClass().addClass(css);
			} else if ($('#hbutton').attr('class') == 'hbutton3') {
				$(obj).attr('title','价格由高到低');
				$('#hbutton').removeClass().addClass('hbutton5');		
			}
		}
	} else {
		$('#hbutton').removeClass().addClass(css);
	}
	doSearch();
}